﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;
using ITPCTaxFormModel;
using System.Data;
using System.Web;

public partial class List : System.Web.UI.Page {
    protected MetaTable table;
    public string ResolveUrl(string url)
    {
        if (url == null) throw new ArgumentNullException("url", "url can not be null");
        if (url.Length == 0) throw new ArgumentException("The url can not be an empty string", "url");

        // there is no ~ in the first character position, just return the url 
        if (url[0] != '~') return url;

        string applicationPath = HttpContext.Current.Request.ApplicationPath;

        // there is just the ~ in the URL, return the applicatonPath 
        if (url.Length == 1) return applicationPath;

        // assume url looks like ~somePage 
        int indexOfUrl = 1;

        // determine the middle character 
        string midPath = (applicationPath.Length > 1) ? "/" : string.Empty;

        // if url looks like ~/ or ~\ change the indexOfUrl to 2 
        if (url[1] == '/' || url[1] == '\\') indexOfUrl = 2;

        return applicationPath + midPath + url.Substring(indexOfUrl);
    }// ResolveUrl

    protected void Page_InitComplete(object sender, EventArgs e)
    {
        // InfoID.Information = "<!--#include FILE='~/DynamicData/CustomPages/Products/Products.htm' -->";
    }
    
    protected void Page_Init(object sender, EventArgs e) {
        table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
        GridView1.SetMetaTable(table, table.GetColumnValuesFromRoute(Context));
        GridDataSource.EntityTypeFilter = table.EntityType.Name;
        /*
        This fixed Microsoft Dynamic Data Entities Bug when you tried to Sort the GridView

        */
        DynamicDataManager1.RegisterControl(GridView1, true /*setSelectionFromUrl*/);
        table = GridDataSource.GetTable();

        if (!Page.IsPostBack)
        {
            GridView1.Sort("ProductID", SortDirection.Descending);
        }


    }

    protected void Page_Load(object sender, EventArgs e) {
        Title = table.DisplayName;
        GridDataSource.Include = table.ForeignKeyColumnsNames;

        // Disable various options if the table is readonly
        if (table.IsReadOnly) {
            GridView1.Columns[0].Visible = false;
            //InsertHyperLink.Visible = false;
            lnkInsrt.Visible = false;
            GridView1.EnablePersistedSelection = false;
        }

        // Initialize the URL for routing to all categories.
        ViewAllLink.NavigateUrl = Request.Path;

        //Visible Insert Button
        if (Request.Url.Query.Contains("ProductCategoryID"))
        {
            lnkInsrt.Visible = false;
            ListHyperLink.Visible = true;
        }
    }

    protected void Label_PreRender(object sender, EventArgs e) {
        Label label = (Label)sender;
        DynamicFilter dynamicFilter = (DynamicFilter)label.FindControl("DynamicFilter");
        QueryableFilterUserControl fuc = dynamicFilter.FilterTemplate as QueryableFilterUserControl;
        if (fuc != null && fuc.FilterControl != null) {
            label.AssociatedControlID = fuc.FilterControl.GetUniqueIDRelativeTo(label);
        }
    }

    protected override void OnPreRenderComplete(EventArgs e) {
        RouteValueDictionary routeValues = new RouteValueDictionary(GridView1.GetDefaultValues());
        //InsertHyperLink.NavigateUrl = table.GetActionPath(PageAction.Insert, routeValues);
        lnkInsrt.HRef = table.GetActionPath(PageAction.Insert, routeValues) + "?TB_iframe=true&keepThis=true&width=600&height=600&modal=true";
        base.OnPreRenderComplete(e);

    }

    protected void DynamicFilter_FilterChanged(object sender, EventArgs e) {
        GridView1.PageIndex = 0;
    }



    

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {                
            HyperLink lnkView = e.Row.FindControl("lnkView") as HyperLink;
            string productid = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ProductID"));
            if (lnkView != null)
                lnkView.NavigateUrl = ResolveUrl("~/" + table.DisplayName + "/PopupDetails.aspx?ProductID=" + productid + "TB_iframe=true&keepThis=true&width=600&height=600");

            HyperLink lnkEdt = e.Row.FindControl("lnkEdt") as HyperLink;
            if (lnkEdt != null)
                lnkEdt.NavigateUrl = ResolveUrl("~/" + table.DisplayName + "/PopupEdit.aspx?ProductID=" + productid + "TB_iframe=true&keepThis=true&width=600&height=600");
        }
    }

    // Utility function to obtain the data entity. This is to avoid the run-time entity 
    // framework conversion error: 
    // "Unable to cast object of type 'System.Web.UI.WebControls.EntityDataSourceWrapper' to 
    // type 'AdventureWorksLT_DataModel.Product'". 
    // This error is issued when using the direct conversion:  
    //  var productItem = (Product)GetDataItem();
    protected TEntity GetDataEntity<TEntity>(object dataItem) where TEntity : class
    {

        TEntity entity = dataItem as TEntity;

        if (entity != null)
        {
            return entity;
        }

        var td = dataItem as ICustomTypeDescriptor;

        if (td != null)
        {
            return (TEntity)td.GetPropertyOwner(null);
        }

        return null;

    }


    // Create route information based on the foreign-key specified 
    // in the DynamicRouteExpression page markup. 
    protected string GetRouteInformation()
    {

        // Retrieves the data entity.
        Product productItem = GetDataEntity<Product>(GetDataItem());

        if (productItem != null)
        {

            RouteValueDictionary rvd = new RouteValueDictionary();
            rvd.Add("ProductCategoryID", productItem.ProductCategoryID);

            string routePath = table.GetActionPath(PageAction.List, rvd);

            return routePath;

        }
        return string.Empty;
    }


    // Get the name of the foreign-key category. 
    protected string GetProductCategory()
    {

        // Retrieves the data entity.
        Product productItem = GetDataEntity<Product>(GetDataItem());

        if (productItem != null)
        {
            return productItem.ProductCategory.Description;
        }
        return string.Empty;
    }

}
